import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Not, Repository } from 'typeorm';
import { GoodsEntity } from './goods.entity';
import { CreateGoodsDto } from './dto/create-goods.dto';

@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(GoodsEntity)
    private readonly goodsRepository: Repository<GoodsEntity>,
  ) {}

  create(createGoodsDto: CreateGoodsDto): Promise<GoodsEntity> {
    return this.goodsRepository.save(createGoodsDto);
  }

  async findGoodsByCondition(userId: number): Promise<GoodsEntity[]> {
    return this.goodsRepository.createQueryBuilder('goods')
      .where('state = :state', { state: 1 })
      .andWhere('business_id = :userId OR buyer = :userId', { userId })
      .getMany();
  }

  async findAll(): Promise<GoodsEntity[]> {
    return this.goodsRepository.find();
  }

  findOne(id: number): Promise<GoodsEntity> {
    return this.goodsRepository.findOneBy({ id: id });
  }
  //我上架的物品
  sellGoods(createGoodsDto:CreateGoodsDto): Promise<GoodsEntity[]> {
    return this.goodsRepository.findBy(createGoodsDto);
  }

  async marketList(businessId: number): Promise<GoodsEntity[]> {
    return this.goodsRepository.find({
      where: {
        businessId: Not(businessId),
        state: 0
      },
    });
  }

  async remove(id: string): Promise<void> {
    await this.goodsRepository.delete(id);
  }

  async findOneByName(goodName: string): Promise<GoodsEntity | undefined> {
    return this.goodsRepository.findOneBy({ goodName: goodName });
  }

  async update(id: number, createGoodsDto: CreateGoodsDto): Promise<GoodsEntity> {
    const good = await this.findOne(id);
    if (!good) {
      throw new Error('good not found');
    }
    Object.assign(good, createGoodsDto);
    return this.goodsRepository.save(good);
  }

}